package xyz.cloorc.xzip.hex

import xyz.cloorc.xzip.Unzip

import java.util.zip.GZIPInputStream

/**
 * Created by Soiff on 2016/4/10.
 *
 * @author : wittcnezh@foxmail.com
 * @version : 1.0
 */
class HexUngzip implements Unzip {
    public void unzip(InputStream is, OutputStream os) {
        final List<Byte> buffer = new ArrayList<Byte>()
        int read
        String b = null
        while ((read = is.read()) != -1) {
            if (32 == read) {
                if (b.length() == 2)
                    buffer.add(Integer.valueOf(b, 16).byteValue())
                else
                    throw new IllegalFormatWidthException(b.length())
                b = null
            } else {
                b = (null == b) ? (char)read : b + (char)read
            }
        }
        final byte[] ba = new byte[buffer.size()];
        for (int i = 0; i < buffer.size(); ++ i)
            ba[i] = buffer[i].byteValue()
        final ByteArrayInputStream bais = new ByteArrayInputStream(ba)
        final GZIPInputStream gis = new GZIPInputStream(bais)

        final StringBuffer sbhex = new StringBuffer()
        final StringBuffer sbasc = new StringBuffer(8)
        String hex;
        int index = 0
        while ((read = gis.read()) != -1) {
            hex = Integer.toHexString(read)
            sbhex.append(hex.length() < 2 ? '0' : "").append(hex).append(' ')
            sbasc.append(32 <= read && read <= 126 ? (char)read : '.')
            if (index == 7) {
                sbhex.append(sbasc).append("\r\n")
                sbasc.delete(0, sbasc.size())
                index = 0
            } else index ++
        }
        os.write(sbhex.toString().getBytes())
    }
}
